var fs = require('fs');
var path = require('path');
var request = require('request');
var file = path.join(__dirname, 'url.txt');
// var file = path.join(__dirname, 'urlxx.txt');

// http://davidwalsh.name/async-generators
// 从这里来看
// 整个流程在main里面，但是驱动过程分散了
// getUrl的回调中，it.next一下
// makeRequest的回调中,it.next一下
// 这里 getUrl, makeRequest 夹杂了 next操作,不是很好
// 更好的版本，type_generator_promise.js
function getUrl() {
	console.log('getUrl');
	fs.readFile(file, 'utf8', function(err, res) {
		it.next({err: err,url: res});
	});
}

function makeRequest(url) {
	console.log('makeRequest');
	url = 'http://haha.foo.bar.com';
	request(url, function(err, res, body) {
		it.next({err: err,body: body});
	});
}

function* main() {
	console.log('main start');
	var result = yield getUrl();
	console.log('result=' , result);
	if (result.err) {
		return console.log('get url err:' + result.err);
	}

	var result2 = yield makeRequest(result.url);
	console.log('result2=' , result2);
	if (result2.err) {
		return console.log('make request err:' + result2.err);
	}
	console.log(result2.body.substring(0,10));
}

var it = main();
it.next();